<?php
function parse_template($tplfile, $templateid, $tpldir)
{
    global $language, $subtemplates, $timestamp;
    $nest = 6;
    $basefile = $file = basename($tplfile, '.php');
    $file == 'header' && CURSCRIPT && $file = 'header_' . CURSCRIPT;
    $subdirectory = str_replace(APP_ROOT . "/" . $tpldir . "/", "", $tplfile);
    $subdirectory = str_replace("/" . $basefile . ".php", ".", $subdirectory);
    $subdirectory = str_replace($basefile . ".php", "", $subdirectory);
    $subdirectory = str_replace("/", ".", $subdirectory);
    $objfile = APP_ROOT . '/cache/templates/' . $subdirectory . $file . '.tpl.php';
    //echo $objfile;
    if (!@$fp = fopen($tplfile, 'r')) {
        $subdirectory = str_replace(".", "", $subdirectory);
        if ($subdirectory != "") {
            //echo $subdirectory;
            $subdirectory .= "/";
        }
        echo "Current template file '/$tpldir/{$subdirectory}{$file}.htm' not found or have no access!";
        exit();
    }
    $template = @fread($fp, filesize($tplfile));
    fclose($fp);
    $var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";
    $const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)";
    $headerexists = preg_match("/{(sub)?template\s+header\}/", $template) || $basefile == 'header_ajax';
    $subtemplates = array();
    for ($i = 1; $i <= 3; $i++) {
        if (strexists($template, '{subtemplate')) {
            $template = @preg_replace("/[\n\r\t]*\{subtemplate\s+([a-z0-9_:>]+)\}[\n\r\t]*/ies", "stripvtemplate('\\1', 1)", $template);
        }
    }
    $template = @preg_replace("/[\n\r\t]*\{csstemplate\}[\n\r\t]*/ies", "loadcsstemplate('\\1')", $template);
    $template = @preg_replace("/([\n\r]+)\t+/s", "\\1", $template);
    $template = @preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $template);
    $template = @preg_replace("/\{lang\s+(.+?)\}/ies", "languagevar('\\1')", $template);
    $template = @preg_replace("/\{faq\s+(.+?)\}/ies", "faqvar('\\1')", $template);
    $template = str_replace("{LF}", "<?=\"\\n\"?>", $template);
    $template = @preg_replace("/\{(\\\$[a-zA-Z0-9_\[\]\'\"\$\.\x7f-\xff]+)\}/s", "<?=\\1?>", $template);
    $template = @preg_replace("/$var_regexp/es", "addquote('<?=\\1?>')", $template);
    $template = @preg_replace("/\<\?\=\<\?\=$var_regexp\?\>\?\>/es", "addquote('<?=\\1?>')", $template);
    $headeradd = $headerexists ? "hookscriptoutput('$basefile');" : '';
    if (!empty($subtemplates)) {
        $headeradd .= "\n0\n";
        foreach ($subtemplates as $fname) {
            $headeradd .= "|| checktplrefresh('$tplfile', '$fname', $timestamp, '$templateid', '$tpldir')\n";
        }
        $headeradd .= ';';
    }
    //$refreshcheckstr="<? if($tplrefresh==1){}? >";
    //if ($tplrefresh == "1") {
    //}
    $template = "<? if(!defined('IN_MYSITE')) exit('Access Denied');if(TPLREFRESH==1){{$headeradd}} ?>\n$template";
    $template = @preg_replace("/[\n\r\t]*\{template\s+([a-z0-9_:]+)\}[\n\r\t]*/ies", "stripvtemplate('\\1', 0)", $template);
    $template = @preg_replace("/[\n\r\t]*\{template\s+(.+?)\}[\n\r\t]*/ies", "stripvtemplate('\\1', 0)", $template);
    $template = @preg_replace("/[\n\r\t]*\{eval\s+(.+?)\}[\n\r\t]*/ies", "stripvtags('<? \\1 ?>','')", $template);
    $template = @preg_replace("/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/ies", "stripvtags('<? echo \\1; ?>','')", $template);
    $template = @preg_replace("/([\n\r\t]*)\{elseif\s+(.+?)\}([\n\r\t]*)/ies", "stripvtags('\\1<? } elseif(\\2) { ?>\\3','')", $template);
    $template = @preg_replace("/([\n\r\t]*)\{else\}([\n\r\t]*)/is", "\\1<? } else { ?>\\2", $template);
    for ($i = 0; $i < $nest; $i++) {
        $template = @preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\}[\n\r]*(.+?)[\n\r]*\{\/loop\}[\n\r\t]*/ies", "stripvtags('<? if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\\3<? } } ?>')", $template);
        $template = @preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}[\n\r\t]*(.+?)[\n\r\t]*\{\/loop\}[\n\r\t]*/ies", "stripvtags('<? if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\\4<? } } ?>')", $template);
        $template = @preg_replace("/([\n\r\t]*)\{if\s+(.+?)\}([\n\r]*)(.+?)([\n\r]*)\{\/if\}([\n\r\t]*)/ies", "stripvtags('\\1<? if(\\2) { ?>\\3','\\4\\5<? } ?>\\6')", $template);
    }
    $template = @preg_replace("/\{$const_regexp\}/s", "<?=\\1?>", $template);
    $template = @preg_replace("/ \?\>[\n\r]*\<\? /s", " ", $template);
    if (!@$fp = fopen($objfile, 'w')) {
        exit("Directory '/cache/templates/' not found or have no access!");
    }
    $template = @preg_replace("/\"(http)?[\w\.\/:]+\?[^\"]+?&[^\"]+?\"/e", "transamp('\\0')", $template);
    $template = @preg_replace("/\<script[^\>]*?src=\"(.+?)\"(.*?)\>\s*\<\/script\>/ise", "stripscriptamp('\\1', '\\2')", $template);
    $template = @preg_replace("/[\n\r\t]*\{block\s+([a-zA-Z0-9_]+)\}(.+?)\{\/block\}/ies", "stripblock('\\1', '\\2')", $template);
    /* 	    if (!str::isStrExist($tplfile, "templates/sysad")) {
                $replstr = array(
                    "\r\n",
                    "\n",
                    "\r"
                );
                //$template=str_replace($replstr,"", $template);

            }
     */
    $template = str_replace("            ", "", $template);
    $template = str_replace("         ", "", $template);
    $template = str_replace("        ", "", $template);
    $template = str_replace("      ", "", $template);
    flock($fp, 2);
    fwrite($fp, $template);
    fclose($fp);
}

function stripvtemplate($tpl, $sub)
{
    $vars = explode(':', $tpl);
    $templateid = 0;
    $tpldir = '';
    if (count($vars) == 2) {
        list($templateid, $tpl) = $vars;
        $tpldir = '/plugins/' . $templateid . '/templates';
    }
    if ($sub) {
        return loadsubtemplate($tpl, $templateid, $tpldir);
    } else {
        return stripvtags("<? include template('$tpl', '$templateid', '$tpldir'); ?>", '');
    }
}

function loadsubtemplate($file, $templateid = 0, $tpldir = '')
{
    global $subtemplates;
    $tpldir = $tpldir ? $tpldir : TPLDIR;
    $templateid = $templateid ? $templateid : TEMPLATEID;
    //$strfile=split(">",$file);
    $strfile = explode(">", $file);
    //echo "-----------------";
    $fsl = count($strfile);
    //		if($fsl!=1)
    //		{
    //			$file=$strfile[0]."/".$strfile[1];
    //		}
    for ($i = 0; $i < $fsl; $i++) {
        if ($i == 0) {
            $splStr1 = "";
            $splStr2 = "";
        } else {
            $splStr1 = "/";
            $splStr2 = ".";
        }
        $tempFile .= $splStr1 . $strfile[$i];
        $includefile .= $splStr2 . $strfile[$i];
    }
    $file = $tempFile;
    $tplfile = APP_ROOT . '/' . $tpldir . '/' . $file . '.php';
    if ($templateid != 1 && !file_exists($tplfile)) {
        $tplfile = APP_ROOT . '/templates/' . $file . '.php';
    }
    $content = @implode('', file($tplfile));
    $subtemplates[] = $tplfile;
    return $content;
}

function cssvtags($curscript, $content)
{
    global $csscurscripts;
    $csscurscripts .= in_array(CURSCRIPT, explode(',', $curscript)) ? $content : '';
}

function transamp($str)
{
    $str = str_replace('&', '&amp;', $str);
    $str = str_replace('&amp;amp;', '&amp;', $str);
    $str = str_replace('\"', '"', $str);
    return $str;
}

function addquote($var)
{
    return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
}

function languagevar($var)
{
    global $templatelang;
    if (isset($GLOBALS['language'][$var])) {
        return $GLOBALS['language'][$var];
    } else {
        $vars = explode(':', $var);
        if (count($vars) != 2) {
            return "!$var!";
        }
        if (in_array($vars[0], $GLOBALS['templatelangs']) && empty($templatelang[$vars[0]])) {
            @include_once APP_ROOT . '/sitedata/plugins/' . $vars[0] . '.lang.php';
        }
        if (!isset($templatelang[$vars[0]][$vars[1]])) {
            return "!$var!";
        } else {
            return $templatelang[$vars[0]][$vars[1]];
        }
    }
}

function stripvtags($expr, $statement)
{
    $expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));
    $statement = str_replace("\\\"", "\"", $statement);
    return $expr . $statement;
}

function stripscriptamp($s, $extra)
{
    $extra = str_replace('\\"', '"', $extra);
    $s = str_replace('&amp;', '&', $s);
    return "<script src=\"$s\"$extra></script>";
}

function stripblock($var, $s)
{
    $s = str_replace('\\"', '"', $s);
    $s = preg_replace("/<\?=\\\$(.+?)\?>/", "{\$\\1}", $s);
    preg_match_all("/<\?=(.+?)\?>/e", $s, $constary);
    $constadd = '';
    $constary[1] = array_unique($constary[1]);
    foreach ($constary[1] as $const) {
        $constadd .= '$__' . $const . ' = ' . $const . ';';
    }
    $s = preg_replace("/<\?=(.+?)\?>/", "{\$__\\1}", $s);
    $s = str_replace('?>', "\n\$$var .= <<<EOF\n", $s);
    $s = str_replace('<?', "\nEOF;\n", $s);
    return "<?\n$constadd\$$var = <<<EOF\n" . $s . "\nEOF;\n?>";
}

function strexists($haystack, $needle)
{
    return !(strpos($haystack, $needle) === FALSE);
}

function checktplrefresh($maintpl, $subtpl, $timecompare, $templateid, $tpldir)
{
    $tplrefresh = TPLREFRESH;
    if (empty($timecompare) || $tplrefresh == 1 || ($tplrefresh > 1 && !($GLOBALS['timestamp'] % $tplrefresh))) {
        if (empty($timecompare) || @filemtime($subtpl) > $timecompare) {
            $templateid = "11";
            parse_template($maintpl, $templateid, $tpldir);
            return TRUE;
        }
    }
    return FALSE;
}

function template($file)
{
    //$inajax=$templateid=null;
    //$file.= $inajax && ($file == 'header' || $file == 'footer') ? '_ajax' : '';
    $tpldir = "templates";
    $templateid = null;
    $includefile = null;
    $dir = APP_ROOT . "/cache/{$tpldir}/";
    if (!is_dir($dir)) {
        mkdir($dir, 0777);
    }
    // $templateid = $templateid ? $templateid : TEMPLATEID;
    $strfile = explode(">", $file);
    $fsl = count($strfile);
    $tempFile = null;
    for ($i = 0; $i < $fsl; $i++) {
        if ($i == 0) {
            $splStr1 = "";
            $splStr2 = "";
        } else {
            $splStr1 = "/";
            $splStr2 = ".";
        }
        $tempFile .= $splStr1 . $strfile[$i];
        $includefile .= $splStr2 . $strfile[$i];
    }
    $file = $tempFile;
    $tplfile = APP_ROOT . '/' . $tpldir . '/' . $file . '.php';
    $filebak = $file;
    $file == 'header' && CURSCRIPT && $file = 'header_' . CURSCRIPT;
    $objfile = APP_ROOT . '/cache/templates/' . $includefile . '.tpl.php';

    if (TPLREFRESH == 1) {
        checktplrefresh($tplfile, $tplfile, @filemtime($objfile), $templateid, $tpldir);
    }
    if (file_exists($objfile)) {
        return $objfile;
    } else {
        echo "errloading";
    }
}

?>
